package com.example.java_gobang.api;

import com.example.java_gobang.dao.UserMapper;
import com.example.java_gobang.model.User;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.NonNull;
import org.springframework.web.bind.annotation.*;


@RestController
@RequestMapping("/user")
public class UserAPI {
    @Resource
    private UserMapper userMapper;

    //登录接口
    @PostMapping("/login")
    @ResponseBody
    public Object login(HttpSession session, @NonNull String username, @NonNull String password){
        User user = userMapper.selectByUsername(username);
        if(user == null){
            System.out.println("用户不存在");
            return new User();
        }
        if(!password.equals(user.getPassword())){
            System.out.println("密码错误");
            return new User();
        }
        session.setAttribute("user", user);
        return user;
    }

    //注册接口
    @PostMapping("/register")
    @ResponseBody
    public Object register(@NonNull String username, @NonNull String password){
        User user = null;
        try {
            user = new User();
            user.setUsername(username);
            user.setPassword(password);
            int row = userMapper.insert(user);
            System.out.println("ret = " + row);
        }catch (org.springframework.dao.DuplicateKeyException e){
            user = new User();
        }
        return user;
    }

    //根据用户名查询
    @GetMapping("/userInfo")
    @ResponseBody
    public Object userInfo(HttpServletRequest request){
        HttpSession session = request.getSession();
        if(session == null){
            return new User();
        }
        User user = (User) session.getAttribute("user");
        if(user == null){
            return new User();
        }
        return userMapper.selectByUsername(user.getUsername());
    }
}
